<template>
  <div class="main-content">
    <!-- 顶部导航栏 -->
    <div class="community-container">
      <!-- 顶部导航栏 -->
      <div class="tab-bar">
        <button class="post-btn" @click="showDialog = true">发表动态</button>
      </div>

      <!-- 动态列表 -->
      <div class="post-list">
        <div v-for="post in posts" :key="post.id" class="post-card">
          <div class="post-header">
            <img :src="post.avatar || '/default-avatar.png'" class="avatar" />
            <div>
              <div class="nickname">
                {{ post.nickname }}
                <el-button size="small" type="primary" class="pm-btn" @click="startPrivateChat(post.user_id, post.nickname, post.avatar)">私信</el-button>
              </div>
              <div class="badge">{{ post.badge }}</div>
            </div>
          </div>
          <div class="post-title">{{ post.title }}</div>
          <div class="post-meta">
            训练时长 {{ post.duration }}　
            平均配速 {{ post.pace }}　
            运动消耗 <b>{{ post.calorie }}</b> 千卡
          </div>
          <div class="post-images" v-if="post.images && post.images.length">
            <img v-for="(img, idx) in post.images" :key="idx" :src="img" class="post-img" />
          </div>
          <div class="post-content">{{ post.content }}</div>
          <div class="post-actions">
            <button @click="toggleLike(post)" :class="{ liked: post.is_liked }">
              👍 {{ post.like_count || 0 }}
            </button>
            <button @click="toggleComments(post)">
              💬 {{ typeof post.comment_count === 'number' ? post.comment_count : 0 }}
            </button>
            <el-dropdown trigger="click">
              <span class="more-btn">&#8942;</span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="+post.user_id === +myUserId" @click="deletePost(post)">删除</el-dropdown-item>
                  <el-dropdown-item @click="dislikePost(post)">不感兴趣</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div v-if="post.showComments" class="comments-section">
            <div v-for="comment in post.comments" :key="comment.id" class="comment-item">
              <img :src="comment.avatar" class="comment-avatar" />
              <span class="comment-nickname">{{ comment.nickname }}</span>
              <span class="comment-content">{{ comment.content }}</span>
              <span class="comment-time">{{ comment.created_at }}</span>
            </div>
            <div class="comment-input">
              <input v-model="post.newComment" placeholder="写评论..." />
              <button @click="submitComment(post)">发送</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 发帖弹窗 -->
      <el-dialog v-model="showDialog" width="500px" :show-close="true" class="post-dialog" center>
        <template #header>
          <span class="dialog-title">快捷发布</span>
        </template>
        <div class="dialog-body">
          <textarea
            v-model="dialogContent"
            placeholder="有什么新鲜事想分享给大家?"
            class="dialog-textarea"
            rows="3"
          ></textarea>
          <div class="dialog-image-section">
            <button class="choose-img-btn" @click="chooseDialogImage">图片</button>
            <input
              ref="dialogFileInput"
              type="file"
              accept="image/*"
              multiple
              style="display: none"
              @change="onDialogFileChange"
            />
            <div v-if="dialogImageUrls.length" class="image-preview">
              <div v-for="(img, idx) in dialogImageUrls" :key="idx" class="img-item">
                <img :src="img" alt="预览" />
                <button class="remove-img-btn" @click="removeDialogImage(idx)">移除</button>
              </div>
            </div>
          </div>
        </div>
        <template #footer>
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="success" @click="publishDialogPost">发送</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import request from '@/utils/request'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import eventBus from '@/utils/eventBus'

const router = useRouter()
const userStore = useUserStore()
const posts = ref([])

// 弹窗相关
const showDialog = ref(false)
const dialogContent = ref('')
const dialogImageUrls = ref([])
const dialogFileInput = ref(null)

function chooseDialogImage() {
  dialogFileInput.value.click()
}

// 上传图片到服务器，返回真实URL
async function uploadImage(file) {
  const formData = new FormData()
  formData.append('file', file)
  const res = await request.post('/api/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  })
  if (res && res.success && res.url) {
    return res.url
  } else {
    throw new Error(res?.msg || '图片上传失败')
  }
}

// 选择图片时，先上传，拿到真实URL后再存
async function onDialogFileChange(e) {
  const files = Array.from(e.target.files)
  for (const file of files) {
    try {
      const url = await uploadImage(file)
      dialogImageUrls.value.push(url)
    } catch (err) {
      ElMessage.error('图片上传失败')
    }
  }
}

function removeDialogImage(idx) {
  dialogImageUrls.value.splice(idx, 1)
}

function parsePostContent(content) {
  // 训练时长
  const durationMatch = content.match(/(?:训练|训练时长|训练了|时长)[：: ]*([0-9]+\s*min|[0-9]+分钟|[0-9]+)/i);
  // 平均配速
  const paceMatch = content.match(/(?:平均配速|配速)[：: ]*([0-9]+[’'′分:]?[0-9]+[″"秒]?)/i);
  // 运动消耗/千卡
  const calorieMatch = content.match(/(?:消耗|运动消耗|消耗了|消耗掉)[：: ]*([0-9]+)\s*千?卡?/i);

  // 只保留正文
  let mainContent = content
    .replace(/(?:训练|训练时长|训练了|时长)[：: ]*([0-9]+\s*min|[0-9]+分钟|[0-9]+)/i, '')
    .replace(/(?:平均配速|配速)[：: ]*([0-9]+[’'′分:]?[0-9]+[″"秒]?)/i, '')
    .replace(/(?:消耗|运动消耗|消耗了|消耗掉)[：: ]*([0-9]+)\s*千?卡?/i, '')
    .replace(/\s+/g, ' ')
    .trim();

  return {
    duration: durationMatch ? durationMatch[1].replace(/分钟|min/, '') : '',
    pace: paceMatch ? paceMatch[1] : '',
    calorie: calorieMatch ? calorieMatch[1] : '',
    content: mainContent
  };
}

async function publishDialogPost() {
  const user_id = localStorage.getItem('userid')
  if (!user_id || user_id === 'guest') {
    ElMessage.warning('您暂未登录，请前往登录')
    return
  }
  if (!dialogContent.value.trim()) {
    ElMessage.warning('内容不能为空')
    return
  }
  const parsed = parsePostContent(dialogContent.value)
  const postData = {
    user_id: Number(user_id),
    title: parsed.content.substring(0, 20) || '动态分享',
    content: parsed.content,
    images: dialogImageUrls.value, // 目前只支持已是URL的图片
    duration: parsed.duration,
    pace: parsed.pace,
    calorie: parsed.calorie
  }
  try {
    const res = await request.post('/api/community/posts/', postData, {
      headers: { 'Content-Type': 'application/json' }
    })
    // 敏感词检测
    if (res && res.code === 400) {
      ElMessageBox.alert(res.msg || '您发表的文章不当，请重新编辑')
      return
    }
    if (res && res.code === 200) {
      ElMessage.success('发表成功')
      showDialog.value = false
      dialogContent.value = ''
      dialogImageUrls.value = []
      fetchPosts()
    } else {
      ElMessage.error(res.msg || '发表失败')
    }
  } catch (e) {
    ElMessage.error('网络错误')
  }
}

onMounted(async () => {
  // 获取社区动态
  await fetchPosts()
  // 调用定位
  userStore.updateLocationByBrowser()

  // 监听事件
  eventBus.on('like', onLike)
  eventBus.on('post', onPost)
  eventBus.on('new-message', onNewMessage)

  if (router.currentRoute && router.currentRoute.value && router.currentRoute.value.query && router.currentRoute.value.query.refresh) {
    fetchPosts()
    router.replace({ path: '/community' }) // 清除query参数
  }
})

onUnmounted(() => {
  eventBus.off('like', onLike)
  eventBus.off('post', onPost)
  eventBus.off('new-message', onNewMessage)
})

function onLike(payload) {
  // 这里可以刷新点赞状态或重新拉取数据
}
function onPost(newPost) {
  // 这里可以刷新帖子列表
}
function onNewMessage(msg) {
  // 这里可以弹窗或刷新消息列表
}

function handleLike(postId) {
  eventBus.emit('like', { postId })
}


async function submitPost() {
  if (!form.value.title || !form.value.content) {
    ElMessageBox.alert('标题和内容不能为空')
    return
  }
  try {
    const res = await request.post('/api/community/posts/', form.value)
    if (res.code === 200 || res.data) {
      ElMessageBox.alert('发表成功')
      // 新动态插入到列表顶部
      posts.value.unshift(res.post || res.data.post || form.value)
      // 清空表单
      form.value = {
        user_id: localStorage.getItem('userid') || '',
        title: '',
        content: '',
        images: [],
        duration: '',
        pace: '',
        calorie: ''
      }
    } else {
      ElMessageBox.alert(res.msg || '发表失败')
    }
  } catch (e) {
    ElMessageBox.alert('网络错误')
  }
}

async function fetchPosts() {
  const res = await request.get('/api/community/posts/')
  posts.value = res

  // 批量获取每条动态的评论数
  for (const post of posts.value) {
    fetchCommentCount(post)
  }
}

// 新增：只获取评论数
async function fetchCommentCount(post) {
  try {
    const res = await request.get('/api/community/comments/', {
      params: { post_id: post.id }
    })
    post.comment_count = res.comments ? res.comments.length : 0
  } catch (e) {
    post.comment_count = 0
  }
}

function toggleComments(post) {
  post.showComments = !post.showComments
  if (post.showComments && !post.comments) {
    fetchComments(post)
  }
}

// 统一token处理
function getAuthToken() {
  let token = localStorage.getItem('token') || '';
  token = token.replace(/^Bearer\s+/i, '');
  return 'Bearer ' + token;
}

async function fetchComments(post) {
  try {
    const res = await request.get('/api/community/comments/', {
      params: { post_id: post.id }
    })
    post.comments = res.comments || []
    // 同步评论数量
    post.comment_count = post.comments.length
  } catch (e) {
    ElMessage.error('评论加载失败')
    post.comments = []
    post.comment_count = 0
  }
}

async function submitComment(post) {
  if (!post.newComment || !post.newComment.trim()) {
    ElMessage.warning('评论不能为空')
    return
  }
  try {
    const res = await request.post('/api/community/comments/', {
      post_id: post.id,
      content: post.newComment,
      parent_id: null
    })
    if (res.code === 200) {
      ElMessage.success('评论成功')
      post.newComment = ''
      fetchComments(post)
      if (typeof post.comment_count === 'number') {
        post.comment_count += 1
      }
    } else {
      ElMessage.error(res.msg || '评论失败')
    }
  } catch (e) {
    ElMessage.error('评论失败')
  }
}

async function toggleLike(post) {
  try {
    if (!post.is_liked) {
      // 点赞
      const res = await request.post('/api/community/like/', {
        post_id: post.id
      })
      if (res.code === 200) {
        post.is_liked = true
        post.like_count = (post.like_count || 0) + 1
      }
    } else {
      // 取消点赞
      const res = await request.post('/api/community/unlike/', {
        post_id: post.id
      })
      if (res.code === 200) {
        post.is_liked = false
        post.like_count = (post.like_count || 1) - 1
      }
    }
  } catch (e) {
    ElMessage.error('操作失败')
  }
}

const myUserId = Number(localStorage.getItem('userid') || 0) // 当前登录用户id

// 删除动态
async function deletePost(post) {
  ElMessageBox.confirm('确定要删除这条动态吗？', '提示', { type: 'warning' })
    .then(async () => {
      try {
        const token = localStorage.getItem('token')
        const res = await request.post(
          'http://127.0.0.1:8000/delete_post/',
          { post_id: post.id },
          {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            }
          }
        )
        if (res && res.code === 200) {
          ElMessage.success('删除成功')
          posts.value = posts.value.filter(p => p.id !== post.id)
        } else {
          ElMessage.error(res.msg || '删除失败')
        }
      } catch (e) {
        ElMessage.error('网络错误')
      }
    })
    .catch(() => {})
}

// 不感兴趣
function dislikePost(post) {
  posts.value = posts.value.filter(p => p.id !== post.id)
  ElMessage.success('已为你减少此类内容推荐')
}

async function startPrivateChat(userId, nickname, avatar) {
  if (!userId) {
    ElMessage.error('无法获取对方用户ID')
    return
  }
  console.log('startPrivateChat 对方用户ID:', userId)
  try {
    const token = localStorage.getItem('token')
    const myUserId = localStorage.getItem('userid')
    const res = await request.get('/chat/rooms/', {
      headers: { Authorization: 'Bearer ' + token }
    })
    // 用 member_ids 判断唯一性
    const ids = [String(myUserId), String(userId)].sort().join(',')
    let room = (res.rooms || []).find(r =>
      r.room_type === 'private' &&
      r.member_count === 2 &&
      Array.isArray(r.member_ids) &&
      r.member_ids.map(String).sort().join(',') === ids
    )
    let room_id
    if (room) {
      room_id = room.id
    } else {
      // 没有则新建
      const createRes = await request.post(
        '/chat/create_room/',
        { user_ids: [myUserId, userId] },
        {
          headers: {
            Authorization: 'Bearer ' + token,
            'Content-Type': 'application/json'
          }
        }
      )
      room_id = createRes.room_id || (createRes.data && createRes.data.room_id)
    }
    if (!room_id) {
      ElMessage.error('创建房间失败')
      return
    }
    router.push({
      name: 'Chat',
      params: { userId },
      query: { nickname, avatar, room_id }
    })
  } catch (e) {
    ElMessage.error('创建房间失败')
  }
}

</script>

<style scoped>
.main-content {
  width: 100%;
  display: flex;
  justify-content: center;
  /* 其它样式 */
}

.community-container {
  max-width: 800px;
  width: 100%;
  margin: 0 auto;
  position: relative;
  min-height: 600px;
  background: transparent;
}

.tab-bar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 16px;
  padding: 0 12px;
  min-height: 48px;
}
.tab {
  margin-right: 24px;
  font-size: 16px;
  color: #333;
  cursor: pointer;
}
.tab.active {
  color: #19c37d;
  font-weight: bold;
  border-bottom: 2px solid #19c37d;
}
.post-btn {
  padding: 6px 16px;
  background: #4fc08d;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.post-list {
  margin-top: 12px;
}
.post-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #0001;
  padding: 24px 28px;
  margin-bottom: 22px;
}
.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.avatar {
  width: 40px; height: 40px; border-radius: 50%; margin-right: 10px;
}
.nickname {
  font-weight: bold;
}
.badge {
  font-size: 12px; color: #888; background: #f3f3f3; border-radius: 8px; padding: 2px 8px; display: inline-block; margin-top: 2px;
}
.post-title {
  font-size: 20px;
  font-weight: bold;
  margin: 8px 0;
}
.post-meta {
  font-size: 14px; color: #666; margin-bottom: 8px;
}
.post-images {
  display: flex; gap: 8px; margin-bottom: 8px;
}
.post-img {
  width: 70px; height: 70px; object-fit: cover; border-radius: 6px;
}
.post-content {
  font-size: 16px;
  color: #333;
}

/* 弹窗美化 */
.post-dialog .el-dialog__header {
  border-bottom: none;
  padding-bottom: 0;
}
.dialog-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}
.dialog-body {
  display: flex;
  flex-direction: column;
  gap: 18px;
  margin-top: 8px;
  align-items: center;
}
.dialog-textarea {
  width: 100%;
  max-width: 400px;
  font-size: 16px;
  padding: 10px;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  resize: none;
  background: #fafbfc;
  transition: border 0.2s;
  min-height: 48px;
  max-height: 90px;
}
.dialog-textarea:focus {
  border: 1.5px solid #19c37d;
  outline: none;
}
.dialog-image-section {
  display: flex;
  align-items: center;
  gap: 12px;
}
.choose-img-btn {
  padding: 7px 18px;
  background: #4fc08d;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}
.choose-img-btn:hover {
  background: #19c37d;
}
.image-preview {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}
.img-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}
.img-item img {
  max-width: 90px;
  max-height: 90px;
  border-radius: 8px;
  box-shadow: 0 1px 6px #0001;
  border: 1px solid #eee;
}
.remove-img-btn {
  background: #f56c6c;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 5px 12px;
  font-size: 13px;
  cursor: pointer;
  transition: background 0.2s;
}
.remove-img-btn:hover {
  background: #d93030;
}

.post-actions {
  display: flex;
  gap: 16px;
  margin-top: 10px;
}
.post-actions button {
  background: none;
  border: none;
  cursor: pointer;
  color: #888;
  font-size: 15px;
}
.post-actions .liked {
  color: #19c37d;
  font-weight: bold;
}
.comments-section {
  margin-top: 8px;
  background: #fafbfc;
  border-radius: 8px;
  padding: 8px 12px;
}
.comment-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}
.comment-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
}
.comment-nickname {
  font-weight: bold;
  color: #333;
}
.comment-content {
  color: #444;
}
.comment-time {
  color: #aaa;
  font-size: 12px;
  margin-left: auto;
}
.comment-input {
  display: flex;
  gap: 8px;
  margin-top: 6px;
}
.comment-input input {
  flex: 1;
  border-radius: 6px;
  border: 1px solid #eee;
  padding: 4px 8px;
}
.comment-input button {
  background: #19c37d;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 4px 12px;
  cursor: pointer;
}

.more-btn {
  cursor: pointer;
  padding: 0 8px;
  font-size: 22px;
  color: #888;
  user-select: none;
}

.pm-btn {
  margin-left: 8px;
  font-size: 12px;
  padding: 2px 10px;
  vertical-align: middle;
}
</style> 